<?php

/**
 * privateMessage actions.
 *
 * @package    sfwixet
 * @subpackage privateMessage
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class privateMessageActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
  		$directory = $request->getParameter("directory",$this->getUser()->getGuardUser()->getMainPrivateMessagesDirectoryId());
  		$pager = $this->getUser()->getGuardUser()->getPrivateMessages($request->getParameter("page",1),$request->getParameter("size",10),$directory);
  		//TODO hacer que aqui lleguen mensajes normales. Cuidado que afecta al widget de mensajes privados
  		foreach ($pager->getResults() as $messageRel)
		{
			$message = $messageRel->getPrivateMessage();
			$textMessage = array();
			$author = $message->getAuthor();
			$authorData = array();
			
			$authorData['name']=$author->getFirstName()." ".$author->getLastName();
			$authorData['id']=$author->getId();
			$authorData['face']=$author->getFace()->getPhotoId();
			
			$textMessage['id'] = $message->getConversationId();
			$textMessage['body'] = $message->getBody();
			$textMessage['author'] = $authorData;
			$textMessage['date'] = $message->getCreatedAt();
			
			$q = Doctrine_Query::create()
  				->select("sum(new) as new")
  				->from('PrivateMessage')
  				->where('conversation_id = ?',$message->getConversationId())
  				->addWhere('user_id = ?',$this->getUser()->getId());
  			$res = $q->execute();

			$textMessage['new'] = $res[0]['new']>0;
			
			$messages[] = $textMessage;
		}
	
    	echo json_encode(array("album"=>Doctrine::getTable("PrivateMessageDirectory")->find($directory)->toArray(),"messages"=>$messages,"pagecount"=>$pager->getLastPage()));
  }
  
  
  public function executeSend(sfWebRequest $request){
  	try{
  		$myId = $this->getUser()->getId();
  		$message = new PrivateMessage();
  		
  		$message->setAuthorId($myId);
  		$message->setBody($request->getParameter("content"));
  		if(is_numeric($request->getParameter("userId"))){	
  			if($myId == $request->getParameter("userId"))
  				throw new Exception(_("You can not send private messages to yourself"));
				$message->setUserId($request->getParameter("userId"));
  				//TODO quitar answerof, puede sobrar porque con ordenadr por id y ver conversacionId vale
  				
  				$q = Doctrine_Query::create()
  				->select("max(conversation_id)+1 as max")
  				->from('PrivateMessage');
  				$res = $q->execute()->toArray();
  				
			    $message->setConversationId($res[0]['max']);
			    $message->save();
			    
			    //Directory relations
			    $myRelation = new PrivateMessageDirectoryMessage();
			    $myRelation->setPrivateMessage($message);
			    $myRelation->setPrivateMessageDirectory($message->getAuthor()->getMainPrivateMessagesSentDirectory());
			    $myRelation->save();
			    
			    $otherRelation = new PrivateMessageDirectoryMessage();
			    $otherRelation->setPrivateMessage($message);
			    $otherRelation->setPrivateMessageDirectory($message->getUser()->getMainPrivateMessagesDirectory());
			    $otherRelation->save();

			    
			 
  			echo json_encode(array("error"=>false));	
  		}else if(is_numeric($conversation = $request->getParameter("conversation"))){
  			$original = Doctrine::getTable("PrivateMessage")->findByConversationId($conversation);
  				
  				$oneMessage = $original->getFirst();
  				//print_r($oneMessage->toArray());
  				if($oneMessage instanceof PrivateMessage && ($oneMessage->getUserId() == $myId || $oneMessage->getAuthorId() == $myId)){
  					//$message->setAnswerOf($answerOf);
  					if($oneMessage->getUserId() == $myId)
  						$message->setUserId($oneMessage->getAuthorId());
  					else
  						$message->setUserId($oneMessage->getUserId());
  						
  						
  					$message->setConversationId($conversation);
  					$message->save();
  					echo json_encode(array("error"=>false));
  				}else throw new Exception(_("You can not answer to this message"));
  		}else throw new Exception(_("Please provide the receiver id or conversation id"));
  		
  	    //Notification for receiver
	    try{
		    $notification = new PrivateMessageNotification();
		    $notification->setConversationId($message->getConversationId());
		    $notification->setUserId($message->getUser()->getId());
		    $notification->save();
	    }catch(Exception $e){
	    	//Notificacion already exists
	    	
	    }
  		
  	}catch(Exception $e){
  		echo json_encode(array("error"=>true,"message"=>$e->getMessage()));
  	}
    return sfView::NONE;
    
  }
  
  public function executeGetConversation(sfWebRequest $request){
  	try{
  		if(is_numeric($conversationId = $request->getParameter("conversation"))){
			$conversation = Doctrine::getTable("PrivateMessage")->findByConversationId($conversationId);
			if($conversation instanceof Doctrine_Collection){
				$message = $conversation->getFirst();
				if($message->getAuthorId() == $this->getUser()->getId() || $message->getUserId() == $this->getUser()->getId()){
					//Check as Read only received messages and remove notification
					$q = Doctrine_Query::create()
					    ->update('PrivateMessage')
					    ->set('new', 0)
					    ->where('conversation_id = ?',$message->getConversationId())
					    ->addWhere('user_id = ?',$this->getUser()->getId());
				    $q->execute();
				    
				    $notifications = Doctrine::getTable("PrivateMessageNotification")->findByDql('conversation_id = ? AND user_id = ?',array($message->getConversationId(),$this->getUser()->getId()));
			    	if($notifications) $notifications->delete();
				//$textMessage['author'] = $authorData;
					//$list = array_reverse($conversation->toArray());
					$list = $conversation->toArray();
					for($i=0; $i<count($list); $i++){
						$author = $conversation->get($i)->getAuthor();
						$list[$i]['author'] = array("user_id"=>$author->getId(),"first_name"=>$author->getFirstName(),"last_name"=>$author->getLastName(),"main_photo_id"=>$author->getMainPhotoId());
					}
					echo json_encode($list);
				}else throw new Exception(_("Permission denied"));
			}else throw new Exception(_("Permission denied"));
  		}else throw new Exception(_("Please provide the conversation id"));
  	}catch(Exception $e){
  		echo json_encode(array("error"=>true,"message"=>$e->getMessage()));
  	}
  	return sfView::NONE;
  }
  

  
  public function executeNewDirectory(sfWebRequest $request){
  	try{
  		if($name = $request->getParameter("name")){
  			$directory = new PrivateMessageDirectory();
  			$directory->setName($name);
  			$directory->setUserId($this->getUser()->getId());
  			$directory->save();
  			echo json_encode(array("error"=>false,"id"=>$directory->getId()));
  		}else throw new Exception(_("Please provide a directory name"));
  	}catch(Exception $e){
  		echo json_encode(array("error"=>true,"message"=>$e->getMessage()));
  	}
  	return sfView::NONE;
  }
  
	public function executeRemoveDirectory(sfWebRequest $request){
  	try{
  		if($id = $request->getParameter("id")){
  			$directory = Doctrine::getTable("PrivateMessageDirectory")->find($id);
  			if($directory->getUserId() == $this->getUser()->getId()){
  				
  				$messages = Doctrine::getTable('PrivateMessageDirectoryMessage')->findByPrivateMessageDirectoryId($directory->getId());
  				if($messages->count() > 0)
  					 throw new Exception(_("This directory contains messages. Please move the messages before remove directory"));
  					 
  				$directory->delete();
  				echo json_encode(array("error"=>false));
  			}else throw new Exception(_("Permission denied"));
  		}else throw new Exception(_("Please provide a directory id"));
  	}catch(Exception $e){
  		echo json_encode(array("error"=>true,"message"=>$e->getMessage()));
  	}
  	return sfView::NONE;
  }
  
  public function executeMoveMessage(sfWebRequest $request){
  	try{
  		if(is_numeric($conversationId = $request->getParameter("conversation")) && is_numeric($directoryId = $request->getParameter("directory"))){
  			$directory = Doctrine::getTable("PrivateMessageDirectory")->find($directoryId);
  			$message = Doctrine::getTable("PrivateMessage")->findByConversationId($conversationId)->getFirst();
  			if($directory->getUserId() == $this->getUser()->getId() && ($message->getAuthorId() == $this->getUser()->getId() || $message->getUserId() == $this->getUser()->getId())){
  				$q = Doctrine_Query::create()
			    ->from('PrivateMessageDirectoryMessage p')
			    ->leftJoin('p.privateMessageDirectory d')
			    ->where('d.user_id = ?',$this->getUser()->getId())
			    ->addWhere('p.private_message_id = ?',$message->getPrivateMessageId());
			    $directoryRel = $q->execute()->getFirst();
  				$directoryRel->setPrivateMessageDirectoryId($directoryId);
  				$directoryRel->save();	
  				echo json_encode(array("error"=>false));
  			}else throw new Exception(_("Permission denied"));
  		}else throw new Exception(_("Please provide the conversation id and message id"));

  	}catch(Exception $e){
  		echo json_encode(array("error"=>true,"message"=>$e->getMessage()));
  	}
  	return sfView::NONE;
  }
  
  public function executeDirectoriesState(sfWebRequest $request){
  		$directories = Doctrine::getTable("PrivateMessageDirectory")->findByUserId($this->getUser()->getId());
  		$data = array();
  		foreach($directories as $directory){
  			$directoryState = $directory->toArray();
  			$directoryState['newMessages'] = $directory->getNewMessagesCount();
  			$data[] = $directoryState;
  		}
  		echo json_encode($data);
  		return sfView::NONE;
  }
  
}
